﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
using PTP.Mock;
using System.IO;

namespace PTP.Usb
{
  [TestFixture]
  public class PipeStreamTest
  {
    [Test]
    [Timeout(2)]
    public void Read(
      [Column(0, 3, 4, 5)]
      int offset,
      [Column(1, 3, 4, 5, 8, 9)]
      int count)
    {
      byte[] data = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
      using (MemoryStream ms = new MemoryStream(data))
      {
        using (MockPipeStream ps = new MockPipeStream(data, 4))
        {
          byte[] pipeBuffer = new byte[data.Length];
          ps.Read(pipeBuffer, offset, count);
          byte[] expectedBuffer = new byte[data.Length];
          ms.Read(pipeBuffer, offset, count);
          Assert.AreElementsEqual<byte>(expectedBuffer, pipeBuffer);
        }
      }
    }

    [Test]
    [Timeout(2)]
    [Row(new byte[] { 0x01, 0x02, 0x03 })]
    [Row(new byte[] { 0x01, 0x03, 0xff, 0x23 })]
    [Row(new byte[] { 0xd2, 0x00, 0x0f, 0x30, 0x03 })]
    [Row(new byte[] { 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x04, 0x02 })]
    [Row(new byte[] { 0x00, 0x00, 0x00, 0xff, 0x00, 0xfe, 0x00, 0x00, 0x00 })]
    public void ReadByte(byte[] data)
    {
      using (MemoryStream ms = new MemoryStream(data))
      {
        using (MockPipeStream ps = new MockPipeStream(data, 4))
        {
          for (int i = 0; i < data.Length; i++)
          {
            Assert.AreEqual<int>(ms.ReadByte(), ps.ReadByte());
          }
        }
      }
    }

    [Test]
    //[Timeout(2)]
    public void Write(
      [Column(new byte[] { 0x01, 0x02, 0x03 })]
      [Column(new byte[] { 0x01, 0x03, 0xff, 0x23 })]
      [Column(new byte[] { 0xd2, 0x00, 0x0f, 0x30, 0x03 })]
      [Column(new byte[] { 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x04, 0x02 })]
      [Column(new byte[] { 0x00, 0x00, 0x00, 0xff, 0x00, 0xfe, 0x00, 0x00, 0x00 })]
      byte[] data,
      [Column(true)]
      [Column(false)]
      bool writeByte)
    {
      using (MockPipeStream ps = new MockPipeStream(new byte[] {}, 4))
      {
        if (writeByte)
        {
          for (int i = 0; i < data.Length; i++)
            ps.WriteByte(data[i]);
        }
        else
        {
          ps.Write(data, 0, data.Length);
        }
        ps.Flush();
        Assert.AreElementsEqual<byte>(data, ps.GetSentData(false));
      }
    }
  }
}
